import { ref, computed, watch } from 'vue'
import { defineStore } from 'pinia'
import router from '@/router'
export const useOlMapStore = defineStore('olMap', () => {
  const adcode = ref('')
  const cityName = ref('')
  const weather = ref('')
  const thisCity = ref('')
  const cities = ref([])
  const seachCity = ref([])
  const isThisCity = computed(() => {
    return cityName.value === thisCity.value
  })
  if (cityName.value === '') {
    $.ajax({
      url: 'https://restapi.amap.com/v3/ip?key=612ca544a280feb306d79c2cd3265c76',
    }).then((res) => {
      if (localStorage.getItem('cityName') && localStorage.getItem('adcode')) {
        cityName.value = localStorage.getItem('cityName')
        adcode.value = localStorage.getItem('adcode')
      } else {
        adcode.value = res.adcode
        cityName.value = res.city
      }
      thisCity.value = res.city
    })
  }

  const handleClick = (city) => {
    if (city !== thisCity.value) {
      cityName.value = city.name
      let index = seachCity.value.findIndex(
        (item) => item.name === city.name.replace('市', '')
      )
      if (index >= 0) {
        seachCity.value.splice(index, 1)
      }
      seachCity.value.unshift(city)
      if (seachCity.value.length > 3) {
        seachCity.value = seachCity.value.slice(0, 3)
      }
      router.push({ name: 'home' })
    } else {
      cityName.value = thisCity.value
      router.push({ name: 'home' })
    }
  }
  const getGeoJson = (key, map, style) => {
    try {
      $.ajax({
        url: `https://restapi.amap.com/v3/geocode/geo?address=${cityName.value}&key=${key}`,
      }).then((res) => {
        adcode.value = res.geocodes[0].adcode
        cityName.value = res.geocodes[0].city
        let center = res.geocodes[0].location.split(',')
        let view = map.getView()
        view.animate({
          center,
          zoom: 8,
          /* 设置漫游的时长 */
          // duration: 3000
          projection: 'EPSG:4326',
        })

        let adJson = `https://geo.datav.aliyun.com/areas_v3/bound/${adcode.value}.json`
        let geoLayer = new ol.layer.Vector({
          source: new ol.source.Vector({
            url: adJson, // 地图来源
            format: new ol.format.GeoJSON(), // 解析矢量地图的格式化类
          }),
        })
        geoLayer.setStyle(style)
        map.addLayer(geoLayer)
      })
    } catch (error) {
      console.log(error)
    }
  }
  watch(cityName, () => {
    localStorage.setItem('cityName', cityName.value)
  })
  watch(adcode, () => {
    localStorage.setItem('adcode', adcode.value)
  })
  watch(
    seachCity,
    () => {
      localStorage.setItem('seachCity', JSON.stringify(seachCity.value))
    },
    { deep: true }
  )
  return {
    adcode,
    cityName,
    weather,
    thisCity,
    cities,
    isThisCity,
    seachCity,
    handleClick,
    getGeoJson,
  }
})
